from docx import Document
from docx.shared import Pt
from typing import Optional
import tempfile, os, re


def _add_markdown_to_docx(doc: Document, text: str) -> None:
    """Very small markdown-to-docx renderer: headings (#), bullets (-/*), bold (**bold**), code fences```."""
    lines = text.splitlines()
    in_code = False
    for raw in lines:
        line = raw.rstrip("\n\r")
        if line.strip().startswith("```"):
            in_code = not in_code
            continue
        if in_code:
            p = doc.add_paragraph()
            run = p.add_run(line)
            run.font.name = "Courier New"
            run.font.size = Pt(10)
            continue

        # Headings
        if line.startswith("### "):
            doc.add_heading(line[4:].strip(), level=3)
            continue
        if line.startswith("## "):
            doc.add_heading(line[3:].strip(), level=2)
            continue
        if line.startswith("# "):
            doc.add_heading(line[2:].strip(), level=1)
            continue

        # Bulleted list
        if line.lstrip().startswith("-") or line.lstrip().startswith("*"):
            text_part = line.lstrip()[1:].strip()
            p = doc.add_paragraph(style="List Bullet")
            _add_inline_bold_runs(p, text_part)
            continue

        # Normal paragraph with bold support
        p = doc.add_paragraph()
        _add_inline_bold_runs(p, line)


def _add_inline_bold_runs(paragraph, text: str) -> None:
    """Split by **bold** and add runs accordingly."""
    # Pattern to find **bold** segments
    parts = re.split(r"(\*\*[^*]+\*\*)", text)
    for part in parts:
        if not part:
            continue
        if part.startswith("**") and part.endswith("**") and len(part) > 4:
            run = paragraph.add_run(part[2:-2])
            run.bold = True
        else:
            paragraph.add_run(part)


def save_report_to_word(report: str, filename: Optional[str] = None) -> str:
    """
    将检验报告内容保存为 Word 文档（带基本 Markdown 样式），返回文件路径
    Args:
        report: 检验报告文本（可包含markdown粗体/标题/列表/代码块）
        filename: 可选，保存的文件名
    Returns:
        文件绝对路径
    """
    doc = Document()
    doc.add_heading('代码检验报告', 0)
    _add_markdown_to_docx(doc, report)
    if not filename:
        filename = f"validate_report_{next(tempfile._get_candidate_names())}.docx"
    temp_dir = tempfile.gettempdir()
    file_path = os.path.join(temp_dir, filename)
    doc.save(file_path)
    return file_path
